package m202405.d12;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/5/13 11:30
 */
public class Q23 {

    public ListNode mergeKLists1(ListNode[] lists) {
        ListNode temp = null;
        for (int i = 0; i < lists.length; i++) {
            temp = merge(temp, lists[i]);
        }
        return temp;
    }

    private ListNode merge(ListNode l1, ListNode l2) {
        ListNode res = new ListNode();
        ListNode rp = res;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                rp.next = l1;
                l1 = l1.next;
                rp = rp.next;
            } else {
                rp.next = l2;
                l2 = l2.next;
                rp = rp.next;
            }
        }
        if (l1 != null) {
            rp.next = l1;
        }
        if (l2 != null) {
            rp.next = l2;
        }
        return res.next;
    }
}
